if not ClosetGnome then return end

local function safeLink(link)
	return gsub(link, "(.*item:.-:.-:.-:.-:.-:.-:.-:.-):.-(|h.*)", "%1%2")
end

local item2set = {}
local function cacheSets()
	for k in pairs(item2set) do item2set[k] = nil end
	for name, set in pairs(ClosetGnome.db.char.set) do
		for _, item in pairs(set) do
			if item then
				item = safeLink(item)
				if not item2set[item] then
					item2set[item] = name
				else
					item2set[item] = item2set[item]..", "..name
				end
			end
		end
	end
end

local select = select
local function tt(tooltip, ...)
	local linkItem = select(2, tooltip:GetItem())
	if not linkItem then 
		return -- yup, it happens.. at least with chatter & hovering over recipe links
	end
	linkItem = safeLink(linkItem)
	if item2set[linkItem] then
		tooltip:AddDoubleLine("ClosetGnome", item2set[linkItem])
	end
end

local function init()
	GameTooltip:HookScript("OnTooltipSetItem", tt)
	cacheSets()
end

ClosetGnome.RegisterCallback("CGTooltip", "UpdateSet", cacheSets)
ClosetGnome.RegisterCallback("CGTooltip", "AddSet", cacheSets)
ClosetGnome.RegisterCallback("CGTooltip", "DeleteSet", cacheSets)
ClosetGnome.RegisterCallback("CGTooltip", "Initialized", init)

